package com.youngjun.user.service.impl;

import com.youngjun.common.exception.CommonExceptionType;
import com.youngjun.common.oss.expection.CommonException;
import com.youngjun.common.oss.manager.OssManager;
import com.youngjun.user.mapper.DocumentMapper;
import com.youngjun.user.pojo.domain.Document;
import com.youngjun.user.pojo.vo.DocumentVO;
import com.youngjun.user.service.DocumentService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

@Service
public class DocumentServiceImpl implements DocumentService {

    private final static String DEFAULT_BUCKET_NAME = "documents";

    @Autowired
    private DocumentMapper documentMapper;

    @Autowired
    private OssManager ossManager;


    @Override
    public DocumentMapper getMapper() {
        return documentMapper;
    }

    @Override
    public DocumentVO upload(MultipartFile multipartFile) {
        Document document = new Document()
                .setName(multipartFile.getOriginalFilename())
                .setContentType(multipartFile.getContentType())
                .setContentSize(multipartFile.getSize());
        insert(document);
        try {
            ossManager.putObject(DEFAULT_BUCKET_NAME, String.valueOf(document.getId()), multipartFile.getInputStream(), multipartFile.getSize(), multipartFile.getContentType());
        } catch (IOException e) {
            e.printStackTrace();
            throw new CommonException(CommonExceptionType.OSS_INSERT_FAILED);
        }
        return new DocumentVO().mapFrom(document);
    }

    @Override
    public void download(String id, HttpServletResponse response) {
        try (InputStream inputStream = ossManager.getObject(DEFAULT_BUCKET_NAME, id)) {
            IOUtils.copy(inputStream, response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
            throw new CommonException(CommonExceptionType.OSS_GET_FAILED);
        }
    }

}